﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmallJob.Data.Interfaces;
using SmallJob.Data;
using SmallJob.Model;
using SmallJob.Services.Interfaces;
using SmallJob.Services.Code;

namespace SmallJob.Services.Implements
{
    public class UserService : RepositoryBase<User>, IUserService
    {
        public UserService(IDatabaseFactory DbFactory)
            : base(DbFactory)
        { }
        public List<User> GetByPage(int page, int pagesize, out int total)
        {
            var list = from u in SmallJobDB.Users
                       orderby u.ID descending
                       select u;
            int skip = (page - 1) * pagesize;
            total = list.ToList().Count;
            return list.Skip(skip).Take(pagesize).ToList();
        }
        public User GetByEmail(string email)
        {
            return (from u in SmallJobDB.Users
                    where u.Email == email && !u.IsLock
                    select u).FirstOrDefault();
        }
        public User Login(string email, string password)
        {
            User result = GetByEmail(email);
            if (result != null && result.Password == UserUtility.Encrypt(password, email) && !result.IsLock)
            {
                return result;
            }
            return null;
        }
        public User GetByFBID(string fbID)
        {
            return (from u in SmallJobDB.Users
                    where u.FbID == fbID && u.IsLock == false
                    select u).FirstOrDefault();
        }
        public Boolean CheckUserNameExist(string username)
        {
            var user = (from u in SmallJobDB.Users
                        where u.UserName == username && u.IsLock == false
                        select u).FirstOrDefault();
            return user != null;

        }
        public User GetByUsername(String username)
        {
            return (from u in SmallJobDB.Users
                    where u.UserName == username && u.IsLock == false
                    select u).FirstOrDefault();
        }
        public List<User> GetAllUser()
        {
            return (from u in SmallJobDB.Users
                    where u.IsLock == false
                    select u).ToList();
        }


        public List<User> GetByPageFilter(int page, int pagesize, out int total, string filter)
        {
            int skip = (page - 1) * pagesize;
            var list = (from d in SmallJobDB.Users
                        where d.ProperName.Contains(filter) || d.UserName.Contains(filter) || d.Email.Contains(filter)
                        orderby d.ID descending
                        select d);

            total = list.ToList().Count;
            var alist = list.ToList();
            return list.Skip(skip).Take(pagesize).ToList();

        }
    }
}
